'use client';

import { useRef, useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import Webcam from 'react-webcam';
import styles from './login.module.css';

// 工具函数
const setToken = (token: string, userData?: any) => {
  localStorage.setItem('userToken', token);
  if (userData) {
    localStorage.setItem('userData', JSON.stringify(userData));
  }
};

const getToken = () => {
  return localStorage.getItem('userToken');
};

const removeToken = () => {
  localStorage.removeItem('userToken');
  localStorage.removeItem('userData');
};

interface LoginFormData {
  name: string;
  pwd: string;
}

const Login = () => {
  const router = useRouter();
  const webcamRef = useRef<Webcam>(null);
  const [isCameraOn, setIsCameraOn] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [loginMethod, setLoginMethod] = useState('account');
  const [countdown, setCountdown] = useState(0);
  const [faceLoginSuccess, setFaceLoginSuccess] = useState(false);
  const [formData, setFormData] = useState<LoginFormData>({
    name: '',
    pwd: ''
  });
  const [message, setMessage] = useState({ type: '', content: '' });

  // 显示消息
  const showMessage = (type: 'success' | 'error' | 'info', content: string) => {
    setMessage({ type, content });
    setTimeout(() => setMessage({ type: '', content: '' }), 3000);
  };

  // 倒计时效果
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (countdown > 0) {
      timer = setInterval(() => {
        setCountdown(prev => prev - 1);
      }, 1000);
    }
    return () => clearInterval(timer);
  }, [countdown]);

  // 人脸识别成功后的跳转
  useEffect(() => {
    if (faceLoginSuccess) {
      const timer = setTimeout(() => {
        router.push('/');
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [faceLoginSuccess, router]);

  const handleFaceLogin = async () => {
    try {
      if (!isCameraOn) {
        setIsCameraOn(true);
        return;
      }

      setLoading(true);
      const imageSrc = webcamRef.current?.getScreenshot();

      if (imageSrc) {
        const response = await fetch('http://127.0.0.1:8000/api/renlianshibie', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            b64: imageSrc.split(',')[1]
          })
        });
        
        const data = await response.json();

        if (data.code === 200) {
          setToken(data.token, { name: data.personName, loginTime: new Date().toISOString() });
          showMessage('success', `欢迎回来，${data.personName}`);
          setFaceLoginSuccess(true);
        } else if (data.code === 400) {
          showMessage('error', '未识别到注册用户');
        } else {
          showMessage('error', '图片中未检测到人脸');
        }
      }
    } catch (error) {
      showMessage('error', '人脸识别服务异常，请稍后再试');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // 自动识别
  useEffect(() => {
    if (isCameraOn && isModalVisible) {
      const interval = setInterval(() => {
        handleFaceLogin();
      }, 2000);
      return () => clearInterval(interval);
    }
  }, [isCameraOn, isModalVisible]);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.name || !formData.pwd) {
      showMessage('error', '没有账号请注册');
      setTimeout(() => {
        router.push('/register');
      }, 2000);
      return;
    }

    try {
      setLoading(true);
      const response = await fetch('http://127.0.0.1:8000/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
      });
      
      const data = await response.json();

      if (data.code === 200) {
        setToken(data.token, { name: data.username || formData.name, loginTime: new Date().toISOString() });
        showMessage('success', '登录成功');
        router.push('/');
      } else {
        showMessage('error', data.message || '账号或密码错误');
      }
    } catch (error) {
      showMessage('error', '登录服务异常，请稍后再试');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleSocialLogin = (type: string) => {
    if (type === '邮箱') {
      router.push('/email-login');
    } else {
      showMessage('info', `${type}登录功能开发中`);
    }
  };

  const handleInputChange = (field: keyof LoginFormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  return (
    <div className={styles.mobileLoginContainer}>
      {/* 消息提示 */}
      {message.content && (
        <div className={`${styles.message} ${styles[message.type]}`}>
          {message.content}
        </div>
      )}

      {/* 背景图片和遮罩层 */}
      <div className={styles.backgroundLayer}>
        <Image 
          src="/img/1.png" 
          alt="background" 
          fill
          className={styles.backgroundImage}
          priority
        />
        <div className={styles.backgroundOverlay}></div>
      </div>
      
      {/* 主要内容 */}
      <div className={styles.mobileContent}>
        <div className={styles.mobileHeader}>
          <h1 className={styles.appTitle}>主题咖APP</h1>
          <p className={styles.appSubtitle}>官方伴侣，出游更省心</p>
        </div>

        <div className={styles.mobileFormContainer}>
          <form onSubmit={handleLogin}>
            <div className={styles.inputGroup}>
              <div className={styles.inputWrapper}>
                <Image src="/img/3.png" alt="用户" width={20} height={20} className={styles.inputIconImg} />
                <input
                  type="text"
                  placeholder="请输入用户名"
                  className={styles.mobileInput}
                  value={formData.name}
                  onChange={(e) => handleInputChange('name', e.target.value)}
                  required
                />
              </div>
              
              <div className={styles.inputWrapper}>
                <Image src="/img/2.png" alt="密码" width={20} height={20} className={styles.inputIconImg} />
                <input
                  type="password"
                  placeholder="请输入密码"
                  className={styles.mobileInput}
                  value={formData.pwd}
                  onChange={(e) => handleInputChange('pwd', e.target.value)}
                  required
                />
              </div>
            </div>
            
            <button 
              type="submit"
              className={styles.mobileLoginBtn} 
              disabled={loading}
            >
              {loading ? '登录中...' : '登录'}
            </button>
          </form>
          
          <div className={styles.otherLogin}>
            <div className={styles.otherLoginDivider}>
              <div className={styles.dividerLine}></div>
              <p className={styles.otherLoginText} onClick={() => router.push('/email-login')}>其他登录方式</p>
              <div className={styles.dividerLine}></div>
            </div>
            <div className={styles.socialLoginIcons}>
              <div className={styles.socialItem} onClick={() => handleSocialLogin('微信')}>
                <div className={styles.socialIconWrapper}>
                  <Image src="/img/wx1.png" alt="微信底图" width={60} height={60} className={styles.socialBg} />
                  <Image src="/img/wx.png" alt="微信" width={30} height={30} className={styles.socialIcon} />
                </div>
                <span className={styles.socialText}>微信</span>
              </div>
              <div className={styles.socialItem} onClick={() => handleSocialLogin('QQ')}>
                <div className={styles.socialIconWrapper}>
                  <Image src="/img/qq1.png" alt="QQ底图" width={60} height={60} className={styles.socialBg} />
                  <Image src="/img/qq.png" alt="QQ" width={30} height={30} className={styles.socialIcon} />
                </div>
                <span className={styles.socialText}>QQ</span>
              </div>
              <div className={styles.socialItem} onClick={() => handleSocialLogin('微博')}>
                <div className={styles.socialIconWrapper}>
                  <Image src="/img/wb1.png" alt="微博底图" width={60} height={60} className={styles.socialBg} />
                  <Image src="/img/wb.png" alt="微博" width={30} height={30} className={styles.socialIcon} />
                </div>
                <span className={styles.socialText}>微博</span>
              </div>
            </div>
          </div>
        </div>
        
        <div className={styles.mobileFooter}>
          <p>© 2020 HTTPS://MMOO.FUN MMO设计</p>
        </div>
      </div>

      {faceLoginSuccess && (
        <div className={styles.loadingOverlay}>
          <p className={styles.successText}>登录成功，正在进入系统</p>
          <div className={styles.spinner}></div>
        </div>
      )}

      {/* 人脸识别弹窗 */}
      {isModalVisible && (
        <div className={styles.modal}>
          <div className={styles.modalContent}>
            <div className={styles.modalHeader}>
              <h3>人脸识别登录</h3>
              <button 
                className={styles.closeBtn}
                onClick={() => {
                  setIsModalVisible(false);
                  setIsCameraOn(false);
                }}
              >
                ×
              </button>
            </div>
            <div className={styles.faceModalContent}>
              {isCameraOn ? (
                <>
                  <Webcam
                    audio={false}
                    ref={webcamRef}
                    screenshotFormat="image/jpeg"
                    className={styles.webcamPreview}
                    videoConstraints={{
                      facingMode: 'user',
                      width: 320,
                      height: 240
                    }}
                  />
                  <p className={styles.faceTip}>请将面部对准框内，系统将自动识别</p>
                </>
              ) : (
                <div className={styles.facePlaceholder}>
                  <div className={styles.cameraIcon}>📷</div>
                  <p>点击下方按钮开启摄像头</p>
                </div>
              )}

              <div className={styles.faceActions}>
                <button
                  className={styles.actionBtn}
                  onClick={() => {
                    if (isCameraOn) {
                      setIsCameraOn(false);
                    } else {
                      setIsCameraOn(true);
                    }
                  }}
                >
                  {isCameraOn ? '关闭摄像头' : '开启摄像头'}
                </button>

                <button
                  className={`${styles.actionBtn} ${styles.primaryBtn}`}
                  onClick={handleFaceLogin}
                  disabled={loading}
                >
                  {loading ? '识别中...' : '立即识别'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Login;